package com.supermap.pisaclient.weather;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lljjcoder.citylist.CityListSelectActivity;
import com.supermap.pisaclient.R;
import com.supermap.pisaclient.common.MainActivity;
import com.supermap.pisaclient.common.SystemConsts;
import com.supermap.util.base.BaseContentFragment;
import com.supermap.util.http.ApiFactory;
import com.supermap.util.http.BaseWeatherResponse;
import com.supermap.util.location.RxLocation;
import com.supermap.util.util.SizeUtils;
import com.supermap.util.weather.ACache;
import com.supermap.util.weather.TimeUtils;
import com.supermap.util.weather.WeatherUtil;
import com.supermap.util.widget.WeatherChartView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Copyright (C) 2017 北京超图软件股份有限公司 版权所有
 * <p>
 * 功能描述：首页天气 作者：李会林
 * <p>
 * 修改人： 修改描述： 修改日期
 */
public class WeatherFragment extends BaseContentFragment {
    private static final String CACHE_WEAHTHER_NAME = "weather_cache";

    private TextView tv_city_name;
    private TextView tvCityName;
    private TextView tvNowWeatherString;
    private TextView tvNowTemp;
    private TextView tvUpdateTime;
    private TextView tvAqi;
    private ACache mCache;
    private HeWeather5 currentWeather;
    private Subscription subscription;
    private LinearLayout dailyForecast;
    private RecyclerView rvSuggestion;
    private SuggestionAdapter suggestionAdapter;
    private String mCity = "";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_weather;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mCache = ACache.get(getActivity());
        tvCityName = findView(R.id.tv_city_name);
        tvNowWeatherString = findView(R.id.tv_weather_string);
        tvNowTemp = findView(R.id.tv_temp);
        tvUpdateTime = findView(R.id.tv_update_time);
        tvAqi = findView(R.id.tv_weather_aqi);
        rvSuggestion = findView(R.id.rvSuggestion);
        tv_city_name = findView(R.id.tv_city_name);
        rvSuggestion.setLayoutManager(new GridLayoutManager(getContext(), 4));
        suggestionAdapter = new SuggestionAdapter(R.layout.item_suggestion, null);
        suggestionAdapter.setDuration(1000);
        suggestionAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvSuggestion.addItemDecoration(new DividerGridItemDecoration(getContext()));
        rvSuggestion.setAdapter(suggestionAdapter);
        tv_city_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoCityChoce();
            }
        });
    }

    private Observable<HeWeather5> getLocalCache() {
        return Observable.unsafeCreate(new Observable.OnSubscribe<HeWeather5>() {

            @Override
            public void call(Subscriber<? super HeWeather5> subscriber) {
                HeWeather5 cacheWeather = (HeWeather5) mCache.getAsObject(CACHE_WEAHTHER_NAME);
                if (cacheWeather == null) {
                    subscriber.onCompleted();
                } else {
                    subscriber.onNext(cacheWeather);
                }
            }
        });
    }

    private Observable<HeWeather5> getFromNetwork(final String city) {
        return RxLocation.get().locate(getActivity())
                .flatMap(new Func1<BDLocation, Observable<BaseWeatherResponse<HeWeather5>>>() {
                    @Override
                    public Observable<BaseWeatherResponse<HeWeather5>> call(BDLocation bdLocation) {

                        if (!TextUtils.isEmpty(city)) {
                            mCity = city;
                        } else {
                            //判断省或者市为空的时候  则会读取上一次定位的位置  如果没有定位到位置 默认设置为重庆
                            if (TextUtils.isEmpty(bdLocation.getCity()) && TextUtils.isEmpty(bdLocation.getDistrict())) {
                                if (!TextUtils.isEmpty(SystemConsts.City)) {
                                    mCity = SystemConsts.City;
                                } else {
                                    mCity = "暂无定位";
                                }
                            } else {
                                if (!TextUtils.isEmpty(bdLocation.getCity())) {
                                    mCity = bdLocation.getCity();
                                } else if (!TextUtils.isEmpty(bdLocation.getDistrict())) {
                                    mCity = bdLocation.getDistrict();
                                } else {
                                    mCity = "暂无定位";
                                }
                            }
                        }
                        tvCityName.setText(mCity);
                        return WeatherUtil.getInstance().getWeatherKey().flatMap(new Func1<String, Observable<BaseWeatherResponse<HeWeather5>>>() {
                            @Override
                            public Observable<BaseWeatherResponse<HeWeather5>> call(String key) {
                                return ApiFactory
                                        .getWeatherController()
                                        .getWeather(key, mCity)
                                        .subscribeOn(Schedulers.io());
                            }
                        });
                    }
                })
                .map(new Func1<BaseWeatherResponse<HeWeather5>, HeWeather5>() {
                    @Override
                    public HeWeather5 call(BaseWeatherResponse<HeWeather5> response) {
                        HeWeather5 heWeather5 = response.HeWeather5.get(0);
                        mCache.put(CACHE_WEAHTHER_NAME, heWeather5, 30 * 60);
                        WeatherUtil.getInstance().saveDailyHistory(heWeather5);
                        return heWeather5;
                    }
                });
    }

    @Override
    protected void lazyFetchData() {
        showRefreshing(true);
        subscription = Observable
                .concat(getLocalCache(), getFromNetwork(mCity))
                .first()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HeWeather5>() {
                    @Override
                    public void onCompleted() {
                        showRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showRefreshing(false);
                        Snackbar.make(getView(), "获取天气失败!", Snackbar.LENGTH_INDEFINITE).setAction("重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                lazyFetchData();
                            }
                        }).setActionTextColor(getActivity().getResources().getColor(R.color.actionColor)).show();
                    }

                    @Override
                    public void onNext(HeWeather5 heWeather5) {
                        showWeather(heWeather5);
                    }
                });

    }

    private void showWeather(HeWeather5 weather) {
        currentWeather = weather;
        tvCityName.setText(weather.getBasic().getCity());
        tvNowWeatherString.setText(weather.getNow().getCond().getTxt());
        tvAqi.setText(weather.getAqi() == null ? "" : weather.getAqi().getCity().getQlty());
        tvNowTemp.setText(String.format("%s℃", weather.getNow().getTmp()));
        String updateTime = TimeUtils.string2String(weather.getBasic().getUpdate().getLoc(), new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()), new SimpleDateFormat("HH:mm", Locale.getDefault()));
        tvUpdateTime.setText(String.format("截止 %s", updateTime));

        dailyForecast = findView(R.id.contentLayout);
        dailyForecast.setPadding(0, SizeUtils.dp2px(getContext(), 16), 0, SizeUtils.dp2px(getContext(), 16));
        dailyForecast.removeAllViews();
        dailyForecast.addView(getChartView(weather));

        List suggestion = new ArrayList();
//        suggestion.add(weather.getAqi());
        suggestion.add(weather.getSuggestion().getAir());
        suggestion.add(weather.getSuggestion().getComf());
        suggestion.add(weather.getSuggestion().getCw());
        suggestion.add(weather.getSuggestion().getDrsg());
        suggestion.add(weather.getSuggestion().getFlu());
        suggestion.add(weather.getSuggestion().getSport());
        suggestion.add(weather.getSuggestion().getTrav());
        suggestion.add(weather.getSuggestion().getUv());
        for (int i = 0; i < suggestion.size(); i++) {
            if (suggestion.get(i) == null)
                suggestion.remove(i);
        }
        suggestionAdapter.setNewData(suggestion);

    }

    private WeatherChartView getChartView(HeWeather5 weather5) {
        WeatherChartView chartView = new WeatherChartView(getContext());
        chartView.setWeather5(weather5);
        return chartView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscription != null && !subscription.isUnsubscribed())
            subscription.unsubscribe();
    }

    /**
     * 切换城市的选项  如果定位失败的话
     */
    private void gotoCityChoce() {
        //估计应该是城市选择的
        Intent intent = new Intent(mContext, CityListSelectActivity.class);
        ((MainActivity) mContext).startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
/*
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");
                    //城市名称
                    if (!TextUtils.isEmpty(cityInfoBean.getName())) {
                        mCity = cityInfoBean.getName();
                        tvCityName.setText(mCity);
                        lazyFetchData();
                    } else {
                        mCity = "数据出错";
                    }
                }
            }
        }
*/
    }


}
